<template>
  <el-upload
    ref="uploadRef"
    action="http://localhost:10520/util/upload"
    list-type="picture-card"
    :auto-upload="false"
    :limit="1"
    method="post"
    :on-success="handleSuccess"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-error="handleError"
    :on-exceed="handleLimitError"
  >
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
      <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
          <el-icon><ZoomIn /></el-icon>
        </span>
        <span v-if="!disabled" class="el-upload-list__item-delete" @click.stop="handleRemove">
          <el-icon><Delete /></el-icon>
        </span>
      </span>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image"/>
  </el-dialog>
</template>

<script lang="ts" setup>

import { ref, onMounted, Ref, watch } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile, UploadInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { deleteFile } from '@/api/utils'
import { headImgStore } from '@/store/tokenStore'

const uploadRef = ref<UploadInstance>()
const headImg = headImgStore()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

// 定义暴露给父组件的方法和事件
const emit = defineEmits(['upload-success'])

// 手动上传的方法
const manualUpload = () => {
    // 直接提交文件，不再尝试获取文件列表
    uploadRef.value!.submit()
}

defineExpose({
  manualUpload
})

// 删除文件并重置组件状态
const handleRemove = () => {
  if (uploadRef.value) {
    uploadRef.value.clearFiles() // 清除文件列表，确保UI更新
  }
}

// 处理上传成功的逻辑
const handleSuccess = (response: any, file: UploadFile) => {
  // 提取文件URL
  const url = response.data; // 假设服务器返回的是{data: 'fileUrl'}
  headImg.setHeadImg(url);
  console.log(url)
  ElMessage.success('上传成功');
  // 发出上传成功的事件，通知父组件
  emit('upload-success', url);
  handleRemove()
}


const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url
  console.log('Previewing file:', file)
  dialogVisible.value = true
}
const handleError = (err: any, file: UploadFile) => {
  console.error('Upload error:', err)
  ElMessage.error('上传失败')
}
const handleLimitError=()=>{
  ElMessage.error('上传文件数量超出限制')
}
</script>
